﻿define(['dojo/_base/declare', 'geomap/plugins/layers/ExGraphicsLayer'], function (
    declare,
    ExGraphicsLayer
) {
    var TextLayer = declare([ExGraphicsLayer], {
        setData: function (mapView, layer) {
            var me = this;
            me.clear();
            if (!mapView) {
                return;
            }
            me.mapView = mapView;
            var mapUtils = mapView.mapUtils;
            me._setLayer(layer);
            var data = $.extend(true, [], layer.layer.data);
            var options = layer.layer || {};
            var lngLatArray = mapUtils.toLngLatArray(mapView, data, options);
            var symbolFieldName = options.symbolFieldName || mapView.getSymbolFieldName();
            var textFieldName = options.textFieldName || mapView.getTextFieldName();
            var spatialReference = me.spatialReference;

            lngLatArray.map(function (lngLat, index) {
                var point = mapUtils.createPoint(mapView, lngLat, { sr: spatialReference });
                var symbol = lngLat[symbolFieldName] || options.symbol || 'common_text';

                mapUtils.getSymbol(mapView, symbol, function (symbol) {
                    if (typeof symbol == 'object') {
                        symbol = mapUtils.$.extend({}, symbol);
                        if (lngLat[textFieldName] || lngLat[textFieldName] == 0) {
                            symbol.setText(lngLat[textFieldName]);
                            var attributes = lngLat;
                            var graphic = mapUtils.createGraphic(mapView, {
                                geometry: point,
                                symbol: symbol,
                                attributes: attributes,
                            });
                            me.add(graphic);
                        }
                    }
                    if (index == lngLatArray.length - 1) {
                        if (typeof options.callback == 'function') {
                            options.callback(layer);
                        }
                    }
                });
            });
        },
        getGraphicLocation: function (mapView, esriEvent) {
            if (!esriEvent || !esriEvent.graphic) {
                return;
            }
            var geometry = esriEvent.graphic.geometry || {};

            var lngFieldName = mapView.getLngFieldName();
            var latFieldName = mapView.getLatFieldName();
            var location = {};
            location[lngFieldName] = geometry.x;
            location[latFieldName] = geometry.y;
            location.sr = geometry.spatialReference;
            return location;
        },
    });
    return TextLayer;
});
